package com.taotao.order.service.impl;

import java.util.Date;
import java.util.Iterator;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.taotao.common.pojo.TaotaoResult;
import com.taotao.mapper.TbOrderItemMapper;
import com.taotao.mapper.TbOrderMapper;
import com.taotao.mapper.TbOrderShoppingMapper;
import com.taotao.order.pojo.OrderInfo;
import com.taotao.order.service.JedisClient;
import com.taotao.order.service.OrderService;
import com.taotao.pojo.TbOrderItem;
import com.taotao.pojo.TbOrderShopping;

@Service
public class OrderServiceImpl implements OrderService {

	// 注入mapper
	@Autowired
	private TbOrderMapper orderMapper;

	@Autowired
	private TbOrderItemMapper orderItemMapper;

	@Autowired
	private TbOrderShoppingMapper shoppingMapper;

	@Autowired
	private JedisClient jedisClient;
	
	@Value("${ORDER_INFO_GEN_KEY}")
	private String ORDER_INFO_GEN_KEY;
	
	@Value("${INIT_ORDER_ID}")
	private String INIT_ORDER_ID;

	@Value("${ORDER_ITEM_GEN_KEY}")
	private String ORDER_ITEM_GEN_KEY;
	@Override
	public TaotaoResult createOrder(OrderInfo info) {
		// 1.插入tbOrder数据-------------------------------------------------

		if (!jedisClient.exists(ORDER_INFO_GEN_KEY)) {
			jedisClient.set(ORDER_INFO_GEN_KEY, INIT_ORDER_ID);
		}

		String orderId = jedisClient.incr(ORDER_INFO_GEN_KEY).toString();
		// info.setBuyerNick(buyerNick); 在controller设置
		info.setCreateTime(new Date());
		info.setOrderId(orderId);
		info.setPostFee("0");
		info.setStatus(1);
		// info.setUserId(userId);由controller设置
		info.setUpdateTime(info.getCreateTime());
		orderMapper.insert(info);
		
		// 2.插入tbOrderItem数据-------------------------------------------
		
		List<TbOrderItem> orderItems = info.getOrderItems();
		Iterator<TbOrderItem> iterator = orderItems.iterator();
		while (iterator.hasNext()) {
			TbOrderItem tbOrderItem = (TbOrderItem) iterator.next();
			//设置订单项的id 通过redis的incr 生成订单项的id
			String incr = jedisClient.incr(ORDER_ITEM_GEN_KEY).toString();
			tbOrderItem.setId(incr);
			tbOrderItem.setOrderId(orderId);
			//插入订单项表
			orderItemMapper.insert(tbOrderItem);
		}

		// 3.插入tb_order_shopping数据-------------------------------------

		TbOrderShopping shopping = info.getOrderShipping();
		//补全其他的属性
		shopping.setOrderId(orderId);
		shopping.setCreated(info.getCreateTime());
		shopping.setUpdated(info.getCreateTime());
		//chauru
		shoppingMapper.insert(shopping);
		//返回需要包含订单的ID
		return TaotaoResult.ok(orderId);
	}

}
